package de.au.fi.imp.reader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.openqa.selenium.By;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.au.fi.calc.CalcHelper;
import de.au.fi.domain.Stock;

public class GrahamInvestorReader extends WebReader {

	Logger log = LoggerFactory.getLogger(this.getClass());

	public GrahamInvestorReader() {
		getFirefoxDriver();
	}

	public List<Stock> getBestPiotroskiStocks() throws Exception {
		driver.get("http://www.grahaminvestor.com/screens/piotroski-scores/");
		List<Stock> stocks = new ArrayList<Stock>();
		String xPathBase = "/html/body/div[2]/div/div[2]/div/div/div[2]/table/tbody/tr%s/td";
		String xPtah = null;
		for (int i = 1; i < 10000; i++) {
			if (i == 1)
				xPtah = String.format(xPathBase, "");
			else
				xPtah = String.format(xPathBase, "[" + i + "]");
			setElementTo(By.xpath(xPtah));
			if(element==null)
				break;
			setElementTo(By.xpath(xPtah));
			String ticker = getText();
			setElementTo(By.xpath(xPtah + "[2]"));
			String name = getText();
			setElementTo(By.xpath(xPtah + "[10]"));
			String piotri = getText();
			Stock stock = new Stock();
			stock.setTicker(ticker);
			stock.setName(name);
			stock.setPiotroskiScore(CalcHelper.getDoubleSafe(piotri));
			stocks.add(stock);
		}
		return stocks;
	}
	
	public List<Stock> addPiotroskiAndAltmannScore(List<Stock> stocks) {
		return addPiotroskiAndAltmannScore(stocks
				.toArray(new Stock[stocks.size()]));
	}

	public List<Stock> addPiotroskiAndAltmannScore(Stock... stocks) {
		for (Stock stock : stocks) {
			try {
				List<Double> scores = getPiotroskiAndAltmannScore(stock
						.getTicker());
				stock.setPiotroskiScore(scores.get(0));
				stock.setAltMannZScore(scores.get(1));
			} catch (Exception e) {
				log.error("error getting scores for={} {}", stock.getTicker(), e.getMessage());
			}
		}
		return Arrays.asList(stocks);
	}

	public List<Double> getPiotroskiAndAltmannScore(String ticker)
			throws Exception {
		List<Double> scores = new ArrayList<Double>();
		driver.get("http://www.grahaminvestor.com/quotes/?ticker="+ticker);

		setElementTo(By.xpath("/html/body/div[2]/div/div[2]/div/div/div/div[2]/center/table/tbody/tr[15]/td[2]/font"));
		scores.add(CalcHelper.getDoubleSafe(getText()));

		setElementTo(By
						.xpath("/html/body/div[2]/div/div[2]/div/div/div/div[2]/center/table/tbody/tr[14]/td[2]/font"));
		scores.add(CalcHelper.getDoubleSafe(getText()));
		log.debug("Set piotroski and Z score to {} for {}",scores, ticker);
		return scores;
	}

}
